package com.weiaibenpao.demo.chislim.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.TwoPointLine;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wlx on 2017/12/11.
 */

public class PolyLinesUtils {
    private final int defaultColor;
    private Context context;
    private LatLonPoint centerLatLng;
    private AMap aMap;
    private List<TwoPointLine> twoPointLineList;
    public final static int POLYLINE_OVER_SUCCESS = 1010;
    public final int POLYLINE_SUCCESS = 100;
    private int unRunColor;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == POLYLINE_SUCCESS) {
                PolylineOptions polygonOptions = (PolylineOptions) msg.obj;
                aMap.addPolyline(polygonOptions);
                Logger.e("wlx", "handleMessage: " + polygonOptions.getPoints().size());
            }


        }
    };
    private PolylineOptions  options = new PolylineOptions();

    public void setColor(int color) {
        if (color!=0){
            this.unRunColor = color;
            return;
        }
        this.unRunColor=defaultColor;

    }

    public PolyLinesUtils(Context context, AMap aMap) {
        this.context = context;
        this.aMap = aMap;
        defaultColor = context.getResources().getColor(R.color.color_un_run);
        unRunColor=defaultColor;

    }

    public void drawLine(final String code, final Handler handler) {
        twoPointLineList = new ArrayList<>();
       if (options!=null&&options.getPoints().size()>0){
           options.getPoints().clear();
       }
       aMap.clear();
//        aMap.clear();
        DistrictSearch search = new DistrictSearch(context);
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(code);
        query.setShowBoundary(true);
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(DistrictResult districtResult) {
                if (districtResult == null || districtResult.getDistrict() == null) {
                    return;
                }
                ArrayList<DistrictItem> districtItems = districtResult.getDistrict();
                DistrictItem districtItem = districtItems.get(0);
                if (districtItem == null) {
                    return;
                }
                centerLatLng = districtItem.getCenter();
                if (centerLatLng != null) {//地图加载时显示行政区域
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 13));
                    Logger.e("getLatitude==" + centerLatLng.getLatitude() + "  getLongitude==" + centerLatLng.getLongitude());
                }
                final DistrictItem finalItem = districtItem;
                //开启线程计算行政区域
                new Thread() {
                    @Override
                    public void run() {
                        String[] boundary = finalItem.districtBoundary();
                        if (boundary.length == 0 || boundary == null) {
                            return;
                        }
                        Logger.e("boundary=="+boundary.length);
                        for (int i = 0; i < boundary.length; i++) {
                            if (((Activity) context).isFinishing()) {
                                return;
                            }

                            String[] lats = boundary[i].split(";");
                            PolylineOptions polylineOptions = new PolylineOptions();

                            boolean isFirst=true;
                            LatLng firstLng=null;
                            LatLng lastLng=null;
                            for (int j = 0; j < lats.length; j++) {
                                if (((Activity) context).isFinishing()) {
                                    return;
                                }
                                //边界个数大于100，且岛屿长度70,舍弃
                                if (boundary.length > 100 && lats.length < 70) {
                                    continue;
                                }
                                String[]  latStart= lats[j].split(",");
                                String[] latEnd;
                                if (j==lats.length-1){
                                    latEnd = lats[0].split(",");
                                }else {
                                    latEnd = lats[j+1].split(",");
                                }


                                LatLng startLng=new LatLng(Double.parseDouble(latStart[1]), Double.parseDouble(latStart[0]));
                                LatLng endLng=new LatLng(Double.parseDouble(latEnd[1]), Double.parseDouble(latEnd[0]));
                                if(isFirst){
                                    firstLng=startLng;
                                    isFirst=false;
                                }

                                TwoPointLine twoPointPolyline= new TwoPointLine();

                                List<LatLng> latLngs = twoPointPolyline.getLatLngs();
                                latLngs.add(startLng);
                                latLngs.add(endLng);
                                twoPointLineList.add(twoPointPolyline);
                                polylineOptions.add(startLng);

                            }
                           if (firstLng!=null){
                               polylineOptions.add(firstLng);
                           }
                            options.addAll(polylineOptions.getPoints());
                            polylineOptions.width(12).color(unRunColor);
                            Message message = Message.obtain();
                            message.obj = polylineOptions;
                            message.what = POLYLINE_SUCCESS;
                            mHandler.sendMessage(message);

                        }

                        //自适应缩放
                        animate();
                        /**
                         * 把所有点集合给调用者
                         */
                        Message message = Message.obtain();
                        message.obj = twoPointLineList;
                        message.what = POLYLINE_OVER_SUCCESS;
                        handler.sendMessage(message);
//                        for (String boundItem : boundary) {
//                            if (((Activity) context).isFinishing()) {
//                                return;
//                            }
//                            String[] lats = boundItem.split(";");
//                            PolylineOptions polylineOptions = new PolylineOptions();
//                            boolean isFirst = true;
//                            LatLng firstLng = null;
//                            for (String latStr : lats) {
//                                if (((Activity) context).isFinishing()) {
//                                    return;
//                                }
//                                //岛屿个数大于100，且岛屿长度70,舍弃
//                                if (boundary.length > 100 && lats.length < 70) {
//                                    continue;
//                                }
//                                String[] lat = latStr.split(",");
//                                polylineOptions.add(new LatLng(Double.parseDouble(lat[1]), Double.parseDouble(lat[0])));
//                                if (isFirst) {
//                                    isFirst = false;
//                                    Logger.e("isFirst=="+(isFirst));
//                                    firstLng = new LatLng(Double.parseDouble(lat[1]), Double.parseDouble(lat[0]));
//                                    continue;
//                                }
//
//                            }
//                            if (firstLng != null) {
//                                Logger.e("firstLng"+(i++));
//                                polylineOptions.add(firstLng);
//                            }
//                            /**
//                             * 把所有的点存起来
//                             *
//                             */
//                            options.addAll(polylineOptions.getPoints());
//                            /**
//                             * 主线程中绘制
//                             */
//                        Message message = Message.obtain();
//                        message.obj = polylineOptions;
//                        message.what = POLYLINE_SUCCESS;
//                        mHandler.sendMessage(message);
////                        twoPointLineList.add(options);
//                        }
//                        //自适应缩放
//                        animate();
////                        /**
////                         * 把所有点集合给调用者
////                         */
//                        Message message = Message.obtain();
//                        message.obj = options;
//                        message.what = POLYLINE_OVER_SUCCESS;
//                        handler.sendMessage(message);
                    }
                }.start();

            }
        });
        if (Utils.isNetWorkConnected()) {
            search.searchDistrictAsyn();
        }

    }

    private void animate() {
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有点的经纬度
        int num = options.getPoints().size();
        for (int i = 0; i < num; i++) {
//            List<LatLng> latLngs = twoPointLineList.get(i).getLatLngs();
            boundsBuilder.include(options.getPoints().get(i));//把所有点都include进去（LatLng类型）

        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 15));//第二个参数为四周留空宽度

    }
}
